(function() {

	GameManager = function(rpc) {
		this.rpc = rpc;
		this.running_games = [];
		// The game the user can see
		this.current_game = null;
		
	};
	
	GameManager.prototype = {
		start : function() {
			this.rpc.subscribe_start_game(this.start_game.bind(this));
			this.rpc.subscribe_disconnected(this.stop.bind(this));
		},
		
		stop : function() {
			this.rpc.unsubscribe_start_game(this.start_game.bind(this));
			if(this.current_game) {
				this.current_game.stop();
				this.current_game = null;
			}
			
			for (var i = 0; i < this.running_games.length; i++) {
				this.running_games[i].stop();
			}	
			this.running_games = [];
			this.close_all_screens();
			$('#screen_login').show();
			
			
		},
		
		show_slider_game : function() {
			
			if(game) {
				game.stop();
			}
			var game = new GameSlider(rpc);
			game.start();
			
		},
		
		start_game : function(game_name, is_background, params) {
			if(this.current_game) {
				this.current_game.stop();
				this.current_game = null;
			}
			var game;
			switch(game_name) {
			case "shake":
				game = new GameShake(rpc);
				break;
			case "shovel":
				game = new GameShovel(rpc);
				break;
			case "button":
				game = new GameButton(rpc);
				break;
			case "swipe":
				game = new GameSwipe(rpc);
				break;
			case "qrcode":
				game = new GameQRCode(rpc);
				break;
			case "slider":
				game = new GameSlider(rpc);
				break;
			case "image_quiz":
				game = new GameImageQuiz(rpc, params);
				break;
			case "flip":
				game = new GameFlip(rpc, is_background);
				break;
			default:
				alert("Game not found: ", game_name);
			}
			if(game) {
				if(!is_background) {
					this.current_game = game;
					this.close_all_screens();
					game.show();
				} else {
					this.running_games.push(game);
				}
				game.start(is_background);
			}
		},
		close_all_screens : function() {
			$("[id*=screen]").css('display', 'none');  
		}
	};
})();